<?php

use Workerman\Worker;
use Workerman\Lib\Timer;

/**
 * 文件监视器，当文件有变化时自动重新加载
 */
class FileMonitor
{
    function run()
    {
        $monitorDir = ROOT_PATH;

        $lastMtime = time();
        $worker = new Worker();
        $worker->name = 'FileMonitor';
        $worker->reloadable = false;

        $worker->onWorkerStart = function()
        {
            global $monitorDir;
            if(!Worker::$daemonize) {
                Timer::add(3, 'check_files_change', [$monitorDir]);
            }
        };

        function check_files_change($monitorDir)
        {
            global $lastMtime;
            // recursive traversal directory
            $dir_iterator = new RecursiveDirectoryIterator($monitorDir);
            $iterator = new RecursiveIteratorIterator($dir_iterator);
            if (!function_exists('posix_kill') || !function_exists('posix_getppid')) {
                return;
            }

            defined('SIGUSR1') || define('SIGUSR1', 10);

            foreach ($iterator as $file)
            {
                if(pathinfo($file, PATHINFO_EXTENSION) !== 'php') {
                    continue;
                }

                if($lastMtime < $file->getMTime()) {
                    echo PHP_EOL . $file." update and reload" . PHP_EOL;
                    // send SIGUSR1 signal to master process for reload
                    posix_kill(posix_getppid(), SIGUSR1);
                    $lastMtime = $file->getMTime();
                    break;
                }
            }
        }
    }
}
